package com.eliza.library.utils.net

import io.ktor.http.HttpHeaders
import io.ktor.http.HttpMethod
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty
import io.ktor.server.plugins.cors.routing.CORS
import io.ktor.server.routing.Route
import io.ktor.server.routing.Routing
import io.ktor.server.routing.route
import io.ktor.server.routing.routing

class BaseServer(private val port: Int) {
    private val server by lazy {
        embeddedServer(Netty, port) {
//            install(CallLogging)
            this.install(CORS) {
                anyHost()
                this.headers.plus(
                    arrayOf(
                        HttpHeaders.ContentType
                    )
                )
                this.methods.plus(
                    arrayOf(
                        HttpMethod.Options, HttpMethod.Put, HttpMethod.Patch, HttpMethod.Delete
                    )
                )

            }
        }
    }

    fun start(module: Application.() -> Unit) {
        module(server.application)
        server.start(wait = true)
    }


    fun setRoute(
        path: String, method: HttpMethod, build: Route.() -> Unit
    ): (Application) -> Unit {
        return fun(application: Application) {
            application.routing { route(path, method, build) }
        }
    }

    fun setRouting(configuration: Routing.() -> Unit): (Application) -> Unit {
        return fun(application: Application) {
            application.routing(configuration)
        }
    }

}

